package com.dc.service;

import com.dc.dao.UserDao;
import com.dc.entity.UserEntity;
import com.dc.utils.PasswordEncryUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class LoginService {

    @Resource
    UserDao userDao;

    @Resource
    JwtTokenService tokenService;

    /**
     * 登录成功，返回 token
     * @param username
     * @param password
     * @return  token, 如果 失败，为空
     */
    public String login(String username, String password) {
        String passwordCry = PasswordEncryUtil.md5Hex(username, password);
        UserEntity user = userDao.findByUserNameAndPassword(username, passwordCry);

        String token = null;

        if(user != null) {
            token = tokenService.generateToken(username);
        }

        return token;
    }

    /**
     * 注册
     * @param userName
     * @param password
     * @param name
     * @return
     */
    public UserEntity register(String userName, String password, String name) {
        UserEntity bean = new UserEntity();
        bean.setUserName(userName);
        bean.setPassword(PasswordEncryUtil.md5Hex(userName, password));
        bean.setName(name);
        return userDao.save(bean);
    }
}
